import React from 'react';
import { Table, Modal, Button, Form, Input } from 'antd';
import { connect } from 'dva';

const FormItem = Form.Item;

function mapStateToProps(state) {
    return {
        cardsList: state.cards.cardsList,
        cardsLoading: state.loading.effects['cards/queryList']
    };
}

class List extends React.Component {
    state = {
        visible: false,
    }
    componentDidMount() {
        this.props.dispatch({
            type: 'cards/queryList'
        });
    }
    // 控制modal弹框的显示与隐藏
    showModal = () => {
        this.setState({ visible: true });
    }
    handleCancel = () => {
        this.setState({ visible: false });
    }
    handleOk = () => {
        const { dispatch, form: { validateFields } } = this.props;
        validateFields((err, value) => {
            if (!err) {
                dispatch({
                    type: 'cards/addOne',
                    payload: value,
                });
                // 重置 `visible` 属性为 false 以关闭对话框
                this.setState({ visible: false });
            }
        });
    }
    columns = [
        {
            title: '名称',
            dataIndex: 'name'
        },
        {
            title: '描述',
            dataIndex: 'desc'
        },
        {
            title: '头像',
            dataIndex: 'url',
            render: value => <a target="_blank" href={value}>{value}</a>
        }
    ]
    render() {
        const { visible } = this.state;
        const { getFieldDecorator } = this.props.form;
        const { cardsList, cardsLoading } = this.props;

        return (
            <div>
                <Table columns={this.columns} dataSource={cardsList} loading={cardsLoading} rowKey="id" />
                <Button onClick={this.showModal}>新建</Button>
                <Modal title="新建记录"
                    visible={visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    >
                    <Form>
                        <FormItem label="名称">
                            {getFieldDecorator('name', {
                                rules: [{ required: true }]
                            })(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem label="描述">
                            {getFieldDecorator('desc')(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem label="头像">
                            {getFieldDecorator('url', {
                                rules: [{ type: 'url' }]
                            })(
                                <Input/>
                            )}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        )
    }
}

export default connect(mapStateToProps)(Form.create()(List));

